/**
 * This file is part of Graylog.
 *
 * Graylog is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Graylog is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Graylog.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.ojoin.trade.common.utils;

import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.StringReader;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.Resources;
 
public class Version  {
	private static final Logger LOG = LoggerFactory.getLogger(Version.class);

	public final String abbrevCommitSha;

	/**
	 * Reads the current version from the classpath, using version.properties
	 * and git.properties.
	 */
	public static final Version CURRENT_CLASSPATH;

	static {
		Version tmpVersion;
		String commitSha = null;
		try {
			final Properties git = new Properties();
			final URL gitResource = Resources.getResource("version.properties");
			final String gitProperties = Resources.toString(gitResource, UTF_8);
			git.load(new StringReader(gitProperties));
			commitSha = git.getProperty("git.commit.id");
			// abbreviate if present and looks like a long sha
			if (commitSha != null && commitSha.length() > 7) {
				commitSha = commitSha.substring(0, 7);
			}
			tmpVersion = new Version(commitSha);
		} catch (Exception e) {
			tmpVersion = new Version("unknown");
			LOG.debug("Git commit details are not available, skipping.", e);
		}
		CURRENT_CLASSPATH =tmpVersion;
	}

	 
	 public Version( String abbrevCommitSha) {
	        this.abbrevCommitSha = abbrevCommitSha;
	    }
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		if (!isNullOrEmpty(abbrevCommitSha)) {
			sb.append(" (").append(abbrevCommitSha).append(')');
		}

		return sb.toString();
	}

	 
	@Override
	public boolean equals(final Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		Version that = (Version) o;

		return   Objects.equals(this.abbrevCommitSha, that.abbrevCommitSha);
	}

	@Override
	public int hashCode() {
		return Objects.hash(abbrevCommitSha);
	}

 
}
